// Copyright (c) [2021] [daifang]
// [Dcomponent] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import './index.less'
import { createPortal } from 'react-dom'
import { useState, useEffect, useRef } from 'react'
import { array, bool, func, object, string } from 'prop-types'
import { throttle } from '../util/Utils'

function Modal (props){
    let { title, children, visible, buttons, cls, target, close, style, size, draggable, fps, position} = props;
    const [animate, setAnimate] = useState('zoomIn')
    const [option,setOption] = useState({x:0,y:0})// 节点x y
    const [start, setStart] = useState({x:0,y:0}) // 记录鼠标点击的x y
    const [end, setEnd] = useState({x:0,y:0})     // 记录结束时的x y
    const refs = useRef(null)                     // 弹窗节点
    let [drag, setDrag] = useState(false)         // 控制是否拖拽
    let [isShow, setIsshow] = useState(false)     // 控制显示
    useEffect(() => {
        if(drag && draggable){
            document.onmousemove = throttle((e)=>{
                dragMove(e, setOption, start, end) 
            },fps==='high'?0:60)

            document.onmouseup = ()=>{
                setDrag(false)
                setEnd({
                    x:option.x,
                    y:option.y
                })
            } 
        }  
        // console.log('init')
        return () => {
            // console.log('returnInit')
            document.onmousemove = null
            document.onmouseup = null
        }
    })
    // 关闭动画
    useEffect(() => {
        // console.log('did',refs)
        let timer
        if(visible){
            setIsshow(true)
            setAnimate('zoomIn')
        }else{
            setAnimate('zoomOut')
            timer = setTimeout(()=>{
                setIsshow(false)
            },300)
        }
        return () => {
            clearTimeout(timer)
        }
    }, [visible])

    useEffect(() => {
        if(refs.current)
        switch(position){
            case 'center':
                autoCenter(refs.current,(X, Y)=>{
                    // 设置弹窗初始位置
                    // console.log(X, Y)
                    setEnd({
                        x:X,y:Y
                    })
                    setOption({
                        x:X,y:Y
                    })
        
                })
            break
            case 'top':
                autoTop(refs.current,(X, Y)=>{
                    // 设置弹窗初始位置
                    // console.log(X, Y)
                    setEnd({
                        x:X,y:Y
                    })
                    setOption({
                        x:X,y:Y
                    })
        
                })
                break
            default:
                break
        }

        return () => {}
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isShow])

    return isShow?createPortal(
            <div 
                ref={refs}
                className={`alert animated faster win-${size} ${cls} ${animate}`} 
                style={{left:`${option.x}rem`,top:`${option.y}rem`,...style}}
            >
                {title && <div 
                    className={`header ${draggable?'draggable':''}`}
                    onMouseDown={(e)=>{
                        if(draggable){
                            // 开始
                            dragStart(e, setStart)
                            setDrag(true)
                        }
                    }}
                    onMouseUp={()=>{
                        // 结束
                        setDrag(false)
                        setEnd({
                            x:option.x,
                            y:option.y
                        })
                    }}
                >
                    <div>{title}</div>
                    <i onClick={
                        ()=>{
                            if(close)
                                close()
                        }
                    } className="iconfont icon-guanbi"></i>
                </div>}
                <div className='body'>{children}</div>
                {buttons?<div className='bottom'>{buttons.map((btn,index)=>{
                    return <div key={index} style={{padding:'0 10px'}}>{btn}</div>
                })}</div>:null}
            </div>, target):null
}

Modal.propTypes = {
    title:string, 
    visible:bool, 
    buttons:array,
    cls:string,
    target:object,
    close:func,
    style:object,
    fps:string,
    position:string
}

Modal.defaultProps = {
    target:document.getElementById('root'),
    cls:'',
    fps:'high',
    position:'center'
}

function dragStart(e, setStart){
    // console.log(e)
    // console.log('开始拖动')
    let {pageX, pageY} = e
    // console.log(pageX,pageY)
    setStart({
        x:pageX,
        y:pageY,
        offsetX:e.target.offsetLeft,
        offsetY:e.target.offsetTop,
    })
}
function dragMove(e, setOption, start, end){
    // e.preventDefault()
    // e.stopPropagation()
    console.log(e)
    let {pageX, pageY} = e
    // console.log(pageX, pageY)
    let fontSize = document.getElementsByTagName('html')[0].style.fontSize.split('px')[0]
    // 换算rem
    setOption({
        x : end.x + (pageX - start.x )/Number(fontSize),
        y : end.y + (pageY - start.y )/Number(fontSize) 
    })
    // console.log('拖动途中')
}

function autoCenter(el, callBack){
    //获取可见窗口大小
    let fontSize = document.getElementsByTagName('html')[0].style.fontSize.split('px')[0]
    let bodyW = document.documentElement.clientWidth;
    let bodyH = document.documentElement.clientHeight;
    //获取对话框宽、高
    let elW = el.offsetWidth;
    let elH = el.offsetHeight;
    let left = ((bodyW - elW)/2)/Number(fontSize);
    let top = ((bodyH - elH)/2)/Number(fontSize);
    callBack(left, top)
};
function autoTop(el, callBack){
    //获取可见窗口大小
    let fontSize = document.getElementsByTagName('html')[0].style.fontSize.split('px')[0]
    let bodyW = document.documentElement.clientWidth;
    // let bodyH = document.documentElement.clientHeight;
    //获取对话框宽、高
    let elW = el.offsetWidth;
    // let elH = el.offsetHeight;
    let left = ((bodyW - elW)/2)/Number(fontSize);
    let top = 2;
    callBack(left, top)
};
export default Modal